import {routes,syncRoutes} from '../../router'
export default {
    namespaced: true, // 具名模块化
    state:{
        routes: []
    },
    mutations: {
        setRoutes(state,newRoutes) {
            state.routes = routes.concat(newRoutes)
        }
    },
    actions: {
        FILTER_ROUTER(context, role) {
            return new Promise((resolve) => {
                // 根据角色过滤路由表
                let newRoutes;
                if(role==='admin') {
                    newRoutes = syncRoutes
                } else {
                    newRoutes = filterRouter(syncRoutes, role)
                }
                context.commit('setRoutes', newRoutes)
                resolve(newRoutes)
            })
            
        }
    }
}
// 返回一个bool
function hasPermission(item, role) {
    // 比较角色
    if(item.meta && item.meta.roles) {
        // some 一真则真
        return item.meta.roles.some(item2 => {
            return item2===role
        })
    } else {
        return true;
    }
}

function filterRouter(router,role){
    const res = [];
    router.forEach(item => {
        const tmp = {...item}
        if(hasPermission(tmp, role)) {
            if(tmp.children) {
                // 递归遍历
                tmp.children = filterRouter(tmp.children, role)
            }
            res.push(tmp)
        }
    })
    return res;
}
